package serveurs;
/**
 *  HttpConnexion
 *
 *
 * @author Peloux Arnaud</a>
 * @version 1.0
 */
import java.io.*;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import java.util.StringTokenizer;



public class HttpConnexion  extends Thread{
	/**
	 * inputs et outputs
	 */
	private Socket sock1;
	private int numConn;
	private long fileLength;
	private BufferedReader in;
	private DataOutputStream out;
	private FileInputStream fis;
	private String  requeteGen,requete;
	private GedServeur ged;
	private boolean isGed=false;
	private String RACINE_HTTP;
	
	public void run(){
		try {
			in = new BufferedReader ( new InputStreamReader(sock1.getInputStream()));			
			out = new DataOutputStream (sock1.getOutputStream());
			//Canaux OK
			lecture();
			sock1.close();	
		} catch (IOException e) {
			
			Exec.logger.fatal("erreur de lecture",e);
		}
		
	}
	
	public HttpConnexion(Socket soc, int NumConnexion, GedServeur ged, String url){
		this.ged = ged;
		sock1 = soc;
		numConn=NumConnexion;
		this.RACINE_HTTP=url;
	}
	
	public void lecture()throws IOException{
		requete= in.readLine();

		if ( requete.startsWith("GET")){
			//Si c'est un GET
			if (recuperationFichier(requete)){
				out.writeBytes(creationEntete(200)+"\r\n");
				if (isGed==false){
					envoiDonnees();
					
				}else if(isGed=true)
				{
					
					ClientAcces ca= new ClientAcces(requete,ged,out);
					envoiDonnees(ca.resultatDemande());
					isGed=false;
				}
				
			}else{
			
				out.writeBytes(creationEntete(404));
			}
		}else if ( requete.startsWith("HEAD")){
			//Si c'est un HEAD
			out.writeBytes(creationEntete(200));
		}else if (requete.startsWith("POST")){
			//Si c'est un POST
			
		}else {
			//Sinon
			out.writeBytes(creationEntete(501));
			}
			
		
		
	}
	
	public void envoiDonnees(){
		byte[] buffer = new byte[1024];
	    int bytes = 0;
	    try {
	    while ((bytes = fis.read(buffer)) != -1) 	
	      out.write(buffer, 0, bytes);  		
	 
	    fis.close();
	    } catch (IOException e) {	
	    	Exec.logger.fatal("erreur d'envoi de fichier",e);
		}
	}
	
	public void envoiDonnees(String tab){
		if (tab==null){
			return;
		}
	    try {
	    	
	      out.writeBytes(tab+"\n");  		
	 
	    //fis.close();
	    } catch (IOException e) {	
	    	Exec.logger.fatal("erreur d'envoi de fichier",e);
		}
	}
	private boolean recuperationFichier(String req){
		String temp = extractionUrl(req);
		
		String[] tabTemp =temp.split("%20");
		
		if (tabTemp[0].equalsIgnoreCase("/AccessGed")){
			isGed=true;
			for (int i=0;i<tabTemp.length;i++)
			
			System.out.println("Acces à la Ged ");
			
			return true;
		}else{
		File fichier = new File(RACINE_HTTP+temp);
		try {
			fis = new FileInputStream(fichier);
		} catch (FileNotFoundException e) {
			Exec.logger.fatal("fichier inconnu",e);
			return false;
		}
		
		
	    
		return true;}
		
		
	}
	
	private String creationEntete(int val){
		StringBuffer entete = new StringBuffer();
		entete.append("HTTP/1.0 ");
		//codes connus
	    switch (val) {
	      case 200:
	    	  entete.append("200 OK");
	        break;
	      case 400:
	    	  entete.append("400 Bad Request");
	        break;
	      case 403:
	    	  entete.append("403 Forbidden");
	        break;
	      case 404:
	    	  entete.append("404 Not Found");
	        break;
	      case 500:
	    	  entete.append("500 Internal Server Error");
	        break;
	      case 501:
	    	  entete.append("501 Not Implemented");
	        break;
	    }
	  
	    if(!isGed){
	    entete.append("\r\nContent-Type:");
	   
	    if(requeteGen.endsWith(".html")||requeteGen.endsWith(".htm")){
	    	entete.append("text/html");
	    }else if (requeteGen.endsWith(".gif")){
	    	entete.append("image/gif");
	    }else if (requeteGen.endsWith(".jpg")||requeteGen.endsWith(".jpeg")){
	    	entete.append("image/jpeg");
	    }else
	    	entete.append("application/octet-stream");
	    }
	    if (requete.endsWith(" HTTP/1.1")& isGed)
	    	entete.append("\r\nContent-Type: application/octet-stream");
	    entete.append("\r\nConnection: close\r\n"); //we can't handle persistent connections
	    entete.append("Server: Rie07JavaWebServer\r\n"); //server name
	    
	    return entete.toString();
	}
	
	private String extractionUrl(String get){
	
		String tmp;
		StringTokenizer st = new StringTokenizer(get);
		st.nextToken(); //passage du GET
		tmp=st.nextToken();	
		if (tmp.compareTo("/")==0){
			tmp="index.html";
		}	//adaptation à la ged
		
		
		
		requeteGen=tmp;
		return tmp;
	}
	
	private String getTime(){
	Calendar calendar = Calendar.getInstance();
	SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z",Locale.US);
	    		    
	    return ("Date: " +dateFormat.format(calendar.getTime()));
	}

}
